import 'dart:convert';
import 'dart:ffi';
import 'package:app/utils/uint.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:bruno/bruno.dart';
import 'package:file_picker/file_picker.dart';

// import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:qiniu_flutter_sdk/qiniu_flutter_sdk.dart';

// import 'package:image_pickers/image_pickers.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../common/colors.dart';
import '../../services/address.dart';
import '../../services/dio_manager.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:get/route_manager.dart';

import '../daily_mission_report_module/my_mission_module/my_missdetails_model.dart';
import '../milepost_module/milepost_view.dart';

class PublishedMissionController extends GetxController {


  BrnStepsController brnStepsController = BrnStepsController(isCompleted: false,
      currentIndex: 0);

  int task_id = 0;
  int project_id = 0;
  String project_name = "";

  PublishedMissionController() : storage = Storage();

  // 用户输入的文件名
  String? key;

  // 用户输入的 partSize
  int partSize = 4;

  // 用户输入的 token
  String? token;

  String? hash_image_path;

  String? qiniu_image_path;

  bool isShowImage = false;

  bool isShowButton = false;

  /// storage 实例
  final Storage storage;

  /// 当前选择的文件
  PlatformFile? selectedFile;


  var activenames = [];
  var activearraids = [];
  var activestrings = "请选择";
  var state = '任务状态';
  var milepostName = '请选择里程碑';

  // 控制器，可以用于取消项目、获取上述的状态，进度等信息
  PutController? putController;

  double intensity = 0.34;

  List<BrnCommonActionSheetItem> actions = [];

  TextEditingController editingController = TextEditingController();

  TextEditingController editingController1 = TextEditingController();

  /// 控制表情隐藏还是显示
  bool isShowEmoji = false;

  String login_uid = "";

  String start_time = "2022-11-11";
  String ended_time = "2022-12-12";

  var startarray = [2022, 11, 11];
  var endedarray = [2022, 12, 12];

  List<String> projectnames = [];

  void getInitData() async {
    print("getInitData==print>>");
    SharedPreferences prefs = await SharedPreferences.getInstance();
    login_uid = prefs.getInt("uid").toString();
    print("login_uid==print>>${login_uid}");
    DateTime dateTime = DateTime.now();
    start_time = dateTime.toString().substring(0, 10);
    ended_time = dateTime.toString().substring(0, 10);
    print("start_time==print>>${start_time}");
    print("end_time==print>>${ended_time}");
  }

  /// 获取我的任务详情数据
  requestMisssionDetails() async {
    var json = await DioManager()
        .kkRequest(Address.missionInfo + task_id.toString(), method: 'get');
    MyMissionDetailsModel _detailsModel = MyMissionDetailsModel.fromJson(json);
    if (_detailsModel.errcode == 0) {
      Data? data = _detailsModel.data;
      project_id = data!.projectId!;
      project_name = data.projectName!;
      editingController.text = data.name.toString();
      editingController1.text = data.description.toString();
      state = data.state!;
      if(state == 'done'){
        brnStepsController.setCurrentIndex(2);
      }
      if(state == 'normal'){
        brnStepsController.setCurrentIndex(0);
      }
      if(state == 'blocked'){
        brnStepsController.setCurrentIndex(1);
      }
      List<UserName>? userName = data.userName;
      activestrings = "";
      activearraids = [];
      userName!.forEach((element) {
        activearraids.add(element.id);
        activestrings += element.name!;
        activestrings += ",";
      });
      start_time = data.planDateBegin.toString().substring(0, 10);
      ended_time = data.planDateEnd.toString().substring(0, 10);

      var startstrings = start_time.split("-");
      startarray = [];
      startstrings.forEach((element) {
        startarray.add(int.parse(element));
      });
      var endstrings = ended_time.split("-");
      endedarray = [];
      endstrings.forEach((element) {
        endedarray.add(int.parse(element));
      });

      refresh();
    }
  }

  ///删除任务
  requestDataDelete() async {
    Map<String, dynamic> hashmap = {};
    hashmap['task_id'] = task_id;
    var formData = FormData.fromMap(hashmap);
    var json = await DioManager().kkRequest(Address.missionUnlink,
        bodyParams: formData, isShowLoad: true);
    if (json['errmsg'] == 'ok') {
      Get.back();
      Get.back(result: 'refresh');
    }
    BotToast.showText(text: json['message']);
  }

  /// 选择任务状态
  tapClickTaskState()async{

   var data = await Get.bottomSheet(Container(
      child:ListView.builder(itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          onTap: (){
            Get.back(result: index==0?'normal':index==1?'blocked':'done');
          },
          child: Container(
            alignment: Alignment.centerLeft,
            height: 50,
            color: Colors.white,
            padding: EdgeInsets.all(10),
            child: index==0?Text('进行中'):index==1?Text('阻塞中'):Text('已完成'),
          ),
        );
      },itemCount: 3,),
      color: Colors.white,
      height: 150+MediaQuery.of(Get.overlayContext!).padding.bottom,
    ));

   print(data);
   if(data == 'normal'){
     state = '进行中';
     brnStepsController.setCurrentIndex(0);
     requestDataWithTaskState('normal');
   }else if(data == 'blocked'){
     state = '阻塞中';
     brnStepsController.setCurrentIndex(1);
     requestDataWithTaskState('blocked');

   }else if(data =='done'){
     state = '已完成';
     brnStepsController.setCurrentIndex(2);
     requestDataWithTaskState('done');
   }

    update();
  }
  /// 标记任务状态
  requestDataWithTaskState(var state)async{

    var params = {
      'task_id':task_id.toString(),
      'state':state,
    };
    var json = await DioManager().kkRequest(Address.projectTaskState,bodyParams:params);
    BotToast.showText(text: json['message']);
  }

  /// 发送请求
  requestDataWithPublish() async {
    Map<String, dynamic> hashmap = {};
    hashmap['name'] = editingController.text;
    hashmap['description'] = editingController1.text;
    hashmap['start_time'] = '$start_time 00:00:00';
    hashmap['end_time'] = '$ended_time 00:00:00';

    if (task_id > 0) {
      hashmap['task_id'] = task_id;
    }
    if (project_id > 0) {
      hashmap['project_id'] = project_id;
      hashmap['project_name'] = project_name;
    }
    if (activearraids.isNotEmpty) {
      var activeids='';
      for (var element in activearraids) {
        activeids += element.toString();
        activeids += ",";
      }
      hashmap['user_ids'] = activeids;
    }
    var json = await DioManager().kkRequestBody(Address.missionCreate,
        params: hashmap, isShowLoad: true);
    if (json['errmsg'] == 'ok') {
      Get.back(result: 'refresh');
    }
    BotToast.showText(text: json['message']);
  }

  /// 点击显示隐藏表情
  tapClickEmojiShow() {
    isShowEmoji = !isShowEmoji;
    print(isShowEmoji);
    update();
  }

  /// 刷新滑动组件
  refreshSlider(double value) {
    intensity = value;
    update();
  }

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getInitData();
    print('Get.arguments===${Get.arguments}');
    task_id = Get.arguments;
    if (task_id > 0) {
      requestMisssionDetails();
    }
  }
}
